package cn.wolfcode.exception;


import cn.wolfcode.qo.JSONResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class HandlerControllerException {
    @ExceptionHandler(RuntimeException.class)
    public Object handlerException(RuntimeException e, HttpServletResponse response, HandlerMethod handler) {
        e.printStackTrace();
        // 判断是否是异步请求 ---- 有没有贴ResponseBody注解
        if (handler.hasMethodAnnotation(ResponseBody.class)) {
            String errorMsg = "操作失败";
            if (e instanceof LogicException) {
                errorMsg = e.getMessage();
            }
            JSONResult json = new JSONResult(false, errorMsg);
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        } else {
            return "common/error";
        }
    }

    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerUnauthorized(UnauthorizedException e, HttpServletResponse response, HandlerMethod handler) {
        e.printStackTrace();
        // 判断是否是异步请求 ---- 有没有贴ResponseBody注解
        if (handler.hasMethodAnnotation(ResponseBody.class)) {
            JSONResult json = new JSONResult(false, "你没有权限操作");
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        } else {
            // 如果不是, 就返回错误的视图页面
            return "common/nopermission";
        }
    }
}
